import { onBeforeUnmount, onMounted } from "vue";

export const usePolling = (callback, { pollingInterval = 1000 }) => {
  let pollingTimer = null;
  const initPolling = () => {
    pollingTimer = setInterval(() => {
      callback();
    }, pollingInterval);
  };
  onBeforeUnmount(() => {
    clearInterval(pollingTimer);
    document.removeEventListener("visibilitychange", visibilitychange, true);
  });
  const visibilitychange = () => {
    const isHidden = document.hidden;
    if (isHidden) {
      clearInterval(pollingTimer);
    } else {
      callback();
      initPolling();
    }
  };
  onMounted(async () => {
    document.addEventListener("visibilitychange", visibilitychange, true);
    initPolling();
  });
};

export const getMarkLineData = data => {
  const { uclValue = null, targetValue = null } = data;
  let arr = [];
  if (typeof uclValue === "number") {
    arr?.push({
      name: "UCL值",
      yAxis: uclValue,
      lineStyle: {
        color: "rgba(245, 158, 11, 1)",
        width: "1",
        type: "dashed"
      },
      animation: false,
      label: {
        position: "insideEndTop",
        color: "rgba(245, 158, 11, 1)",
        fontSize: 10
      }
    });
  }
  if (typeof targetValue === "number") {
    arr?.push({
      name: "Target值",
      yAxis: targetValue,
      lineStyle: {
        color: "rgba(245, 158, 11, 1)",
        width: "1",
        type: "dashed"
      },
      animation: false,
      label: {
        position: "insideEndTop",
        color: "rgba(245, 158, 11, 1)",
        fontSize: 10
      }
    });
  }
  return arr;
};
